/**
 * 作品相关接口
 */

import { get, post, del } from '@/utils/request'
import { BASE_URL } from '@/config/env'

// 作品分类枚举
export enum WorkCategoryEnum {
  FOOD = 'food',        // 美食
  HEALTH = 'health',    // 养生
  TRAVEL = 'travel'     // 旅行
}

// 作品状态枚举
export enum WorkStatusEnum {
  DRAFT = 'draft',           // 草稿
  PUBLISHED = 'published',   // 已发布
  ARCHIVED = 'archived'       // 已归档
}

// 媒体类型枚举
export enum MediaTypeEnum {
  IMAGE = 'image',  // 图片
  VIDEO = 'video'   // 视频
}

// 作者信息
export interface AuthorInfo {
  id: number
  username: string
  avatar?: string
}

// 作品信息
export interface WorkInfo {
  id: number
  title: string
  description: string
  category: WorkCategoryEnum
  status: WorkStatusEnum
  isPublic: boolean
  mediaType: MediaTypeEnum
  imagesUrls?: string[]
  videoUrl?: string
  videoCover?: string
  tags?: string[]
  viewsCount: number
  likesCount: number
  collectionsCount: number
  commentsCount: number
  sharesCount: number
  authorId: number
  location?: string
  latitude?: number
  longitude?: number
  publishedAt?: string
  createdAt: string
  updatedAt: string
  author?: AuthorInfo
  isLiked?: boolean  // 当前用户是否已点赞
  isCollected?: boolean  // 当前用户是否已收藏
}

// 作品列表响应
export interface WorksListResponse {
  data: WorkInfo[]
  total: number
  page: number
  limit: number
  totalPages: number
}

// 获取作品列表参数
export interface GetWorksListParams {
  page?: number
  limit?: number
  category?: WorkCategoryEnum | string
  status?: WorkStatusEnum
  keyword?: string  // 搜索关键词
}

/**
 * API 响应格式
 */
interface ApiResponse<T> {
  success: boolean
  statusCode: number
  message: string
  data: T
}

/**
 * 获取作品列表
 */
export const getWorksList = async (params?: GetWorksListParams): Promise<WorksListResponse> => {
  // GET 请求的参数通过 URL 查询字符串传递
  const queryParams: any = {}
  if (params?.page) queryParams.page = String(params.page)
  if (params?.limit) queryParams.limit = String(params.limit)
  if (params?.category) queryParams.category = params.category
  if (params?.status) queryParams.status = params.status
  if (params?.keyword) queryParams.keyword = params.keyword

  // 构建查询字符串
  const queryString = Object.keys(queryParams)
    .map(key => `${encodeURIComponent(key)}=${encodeURIComponent(queryParams[key])}`)
    .join('&')

  const url = `/works/list${queryString ? `?${queryString}` : ''}`

  const response = await get<ApiResponse<WorksListResponse>>(url, undefined, {
    showLoading: false
  })

  // 返回 data 字段中的实际数据
  return response.data
}

/**
 * 获取美食列表（便捷方法）
 */
export const getFoodList = (page: number = 1, limit: number = 10, keyword?: string): Promise<WorksListResponse> => {
  return getWorksList({
    page,
    limit,
    category: WorkCategoryEnum.FOOD,
    keyword
  })
}

/**
 * 获取作品详情
 */
export const getWorkDetail = async (id: number): Promise<WorkInfo> => {
  const response = await get<ApiResponse<WorkInfo>>(`/works/${id}`, undefined, {
    showLoading: true,
    loadingText: '加载中...'
  })

  // 返回 data 字段中的实际数据
  return response.data
}

/**
 * 切换点赞状态响应
 */
export interface ToggleLikeResponse {
  action: 'liked' | 'unliked'
  message: string
  isLiked: boolean
}

/**
 * 切换收藏状态响应
 */
export interface ToggleCollectResponse {
  action: 'collected' | 'uncollected'
  message: string
  isCollected: boolean
}

/**
 * 切换点赞状态（推荐使用，自动判断点赞/取消）
 */
export const toggleLike = async (id: number): Promise<ToggleLikeResponse> => {
  const response = await post<ApiResponse<ToggleLikeResponse>>(
    `/works/${id}/toggle-like`,
    undefined,
    {
      showLoading: false
    }
  )

  return response.data
}

/**
 * 点赞作品
 */
export const likeWork = async (id: number): Promise<void> => {
  const response = await post<ApiResponse<void>>(
    `/works/${id}/like`,
    undefined,
    {
      showLoading: false
    }
  )

  return response.data
}

/**
 * 取消点赞
 */
export const unlikeWork = async (id: number): Promise<void> => {
  const response = await del<ApiResponse<void>>(
    `/works/${id}/like`,
    undefined,
    {
      showLoading: false
    }
  )

  return response.data
}

/**
 * 切换收藏状态（推荐使用，自动判断收藏/取消）
 */
export const toggleCollect = async (id: number): Promise<ToggleCollectResponse> => {
  const response = await post<ApiResponse<ToggleCollectResponse>>(
    `/works/${id}/toggle-collect`,
    undefined,
    {
      showLoading: false
    }
  )

  return response.data
}

/**
 * 收藏作品
 */
export const collectWork = async (id: number): Promise<void> => {
  const response = await post<ApiResponse<void>>(
    `/works/${id}/collect`,
    undefined,
    {
      showLoading: false
    }
  )

  return response.data
}

/**
 * 取消收藏
 */
export const uncollectWork = async (id: number): Promise<void> => {
  const response = await del<ApiResponse<void>>(
    `/works/${id}/collect`,
    undefined,
    {
      showLoading: false
    }
  )

  return response.data
}

/**
 * 创建作品请求参数
 */
export interface CreateWorkParams {
  title: string
  description: string
  category: WorkCategoryEnum
  status?: WorkStatusEnum
  isPublic?: boolean
  mediaType: MediaTypeEnum
  imagesUrls?: string[]
  videoUrl?: string
  videoCover?: string
  tags?: string[]
  location?: string
  latitude?: number
  longitude?: number
}

/**
 * 创建作品
 */
export const createWork = async (params: CreateWorkParams): Promise<WorkInfo> => {
  const response = await post<ApiResponse<WorkInfo>>(
    '/works/create',
    params,
    {
      showLoading: true,
      loadingText: '发布中...'
    }
  )

  return response.data
}

/**
 * 上传文件（图片或视频）
 */
export const uploadFile = async (filePath: string, fileType: 'image' | 'video'): Promise<string> => {
  return new Promise((resolve, reject) => {
    const token = uni.getStorageSync('accessToken') || ''

    uni.uploadFile({
      url: `${BASE_URL}/upload/${fileType}`,
      filePath: filePath,
      name: 'file',
      header: {
        'Authorization': `Bearer ${token}`
      },
      success: (res) => {
        try {
          const data = JSON.parse(res.data)
          if (data.success && data.data && data.data.url) {
            resolve(data.data.url)
          } else {
            reject(new Error(data.message || '上传失败'))
          }
        } catch (e) {
          // 如果后端直接返回URL字符串
          if (res.data && typeof res.data === 'string' && res.data.startsWith('http')) {
            resolve(res.data)
          } else {
            reject(new Error('上传失败：响应格式错误'))
          }
        }
      },
      fail: (err) => {
        console.error('上传文件失败:', err)
        reject(new Error('上传失败，请检查网络连接'))
      }
    })
  })
}

/**
 * 获取当前用户的收藏列表
 */
export const getMyCollections = async (page: number = 1, limit: number = 10): Promise<WorksListResponse> => {
  const queryParams = `page=${page}&limit=${limit}`
  const response = await get<ApiResponse<WorksListResponse>>(
    `/works/my-collections?${queryParams}`,
    undefined,
    {
      showLoading: false
    }
  )
  return response.data
}

/**
 * 获取当前用户的草稿箱
 */
export const getMyDrafts = async (page: number = 1, limit: number = 10): Promise<WorksListResponse> => {
  const queryParams = `page=${page}&limit=${limit}`
  const response = await get<ApiResponse<WorksListResponse>>(
    `/works/my-drafts?${queryParams}`,
    undefined,
    {
      showLoading: false
    }
  )
  return response.data
}

/**
 * 获取当前用户已发布的作品
 */
export const getMyPublishedWorks = async (page: number = 1, limit: number = 10): Promise<WorksListResponse> => {
  const queryParams = `page=${page}&limit=${limit}&status=${WorkStatusEnum.PUBLISHED}`
  const response = await get<ApiResponse<WorksListResponse>>(
    `/works/my-works?${queryParams}`,
    undefined,
    {
      showLoading: false
    }
  )
  return response.data
}

export default {
  getWorksList,
  getFoodList,
  getWorkDetail,
  toggleLike,
  likeWork,
  unlikeWork,
  toggleCollect,
  collectWork,
  uncollectWork,
  createWork,
  uploadFile,
  getMyCollections,
  getMyDrafts,
  getMyPublishedWorks
}

